package com.distribute.framework.core.web.servlet.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.distribute.framework.core.util.zip.ZipEntry;
import com.distribute.framework.core.util.zip.ZipOutputStream;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.web.helper.ConfigHelper;
import com.distribute.framework.core.web.helper.FileHelper;
import com.distribute.framework.core.web.helper.JsonHelper;
import com.distribute.framework.core.web.helper.ParamHelper;
import com.distribute.framework.core.web.helper.WebHelper;
import com.distribute.framework.core.web.servlet.upload.editor.ImageDim;

@SuppressWarnings("serial")
public class UpLoadServlet extends HttpServlet {
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setHeader("Access-Control-Allow-Origin", "*");	
		
		Map params = request.getParameterMap();
		Integer cx=ParamHelper.getInteger(params, "cx");
		Integer cy=ParamHelper.getInteger(params, "cy");
		
		Boolean bZip = WebHelper.equals(request.getParameter("zip"), "true") ;
			
		UpLoadProgress progress = new UpLoadProgress();
		progress.setComplete(false);
		progress.setLength(request.getContentLength());
		
		String sApp = request.getParameter("app");//上传应用
		if(WebHelper.empty(sApp)){
			Logger.getRootLogger().error("未指定上传应用名称,设置默认的应用[attached]");
			sApp="attached";
		}
		
		Map jsonMap=new HashMap();
		
		if(request.getContentLength()<0){//上传文件太大	
			Logger.getRootLogger().error("无法计算大小，可能上传文件太大");
			progress.setError("无法计算大小，可能上传文件太大");
			progress.setComplete(true);			
			jsonMap.put("message", "无法计算大小，可能上传文件太大");
			jsonMap.put("error", 1);
			WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");						
			return;
		}
		
		final Long max_size=ConfigHelper.GetLong("upload.max");//上传文件的最大字节数
		String upload_forder=ConfigHelper.GetString("upload.forder");//上传图片保存的路径
		String upload_domain=ConfigHelper.GetString("upload.domain");//图片服务的域名地址	
		
		if(max_size!=null && request.getContentLength()>max_size){//上传文件太大	
			Logger.getRootLogger().error("上传失败，上传文件太大");
			progress.setError("上传失败，上传文件太大!");
			progress.setComplete(true);
			jsonMap.put("message", "上传失败，上传文件太大");
			jsonMap.put("error", 1);
			WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");
			return;
		}
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setProgressListener(progress);
		upload.setHeaderEncoding("UTF-8");
		
		if(WebHelper.empty(upload_forder)){
			Logger.getRootLogger().error("未配置upload.forder");
			progress.setError("未配置upload.forder");
			progress.setComplete(true);
			jsonMap.put("message", "未配置upload.forder");
			jsonMap.put("error", 1);
			WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");
			return;
		}
		upload_forder=upload_forder.replaceAll("\\\\", "/");		
		if(!upload_forder.endsWith("/"))
			upload_forder+="/";
		
		if(WebHelper.empty(upload_domain)){
			Logger.getRootLogger().error("未配置upload.domain");
			progress.setError("未配置upload.domain");
			progress.setComplete(true);
			jsonMap.put("message", "未配置upload.domain");
			jsonMap.put("error", 1);
			WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");
			return;
		}
		
		List items=null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e1) {
			e1.printStackTrace();
			Logger.getRootLogger().error("解析文件时出错");
			progress.setError("解析文件时出错");
			progress.setComplete(true);			
			
			jsonMap.put("message", "解析文件时出错");
			jsonMap.put("error", 1);
			WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");
			return;
		}
		Iterator itr = items.iterator();
		while(itr.hasNext()) {//目前只支持一个文件上传
			FileItem item = (FileItem) itr.next();
			long fileSize = item.getSize();
			if (!item.isFormField()) {				
				String fileExt = item.getName().substring(item.getName().lastIndexOf(".") + 1).toLowerCase();				
				String filePah=sApp+"/";
				String fileName=new SimpleDateFormat("HHmmssS"+WebHelper.rand(999)).format(new Date())+"."+(bZip?"zip":fileExt);
				//String fileName=new SimpleDateFormat("HHmmssS"+WebHelper.rand(999)).format(new Date())+"."+fileExt;
				File uploadedFile=null;
				try{
					new File(upload_forder+filePah).mkdirs();
					uploadedFile = new File(upload_forder+filePah, fileName);
					/*if(bZip)//如果指定要压缩成压缩文件
						WriteZipFile(item,uploadedFile);
					else
						item.write(uploadedFile);*/
					item.write(uploadedFile);
					
					progress.setPath(upload_forder+filePah+fileName);
					progress.setUrl(upload_domain+filePah+fileName);
					
					progress.setComplete(true);
					
					if(cx!=null && cy!=null && cx>0 && cy>0){
						//TODO:如果指定略缩图大小，创建略缩图
					}					
					
					Logger.getRootLogger().info("上传文件成功,保存在 - "+upload_forder+filePah+fileName);						
				}catch(Exception e){
					e.printStackTrace();
					Logger.getRootLogger().error("上传文件过程中出现系统错误.移除该文件...");
					progress.setError("上传文件过程中出现系统错误");
					if(uploadedFile!=null)
						uploadedFile.delete();
					progress.setComplete(true);					
					
					jsonMap.put("message", "上传文件过程中出现系统错误");
					jsonMap.put("error", 1);
					WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");
					return;
				}
			}
		}
		
		jsonMap.put("message", "文件上传成功");
		jsonMap.put("error", 0);
		jsonMap.put("url", progress.getUrl());
		WebHelper.SendAjax(JsonHelper.json(jsonMap), "UTF-8");
	}
	
	
}